import axios from './http'
import Data from '@/utils/data'

class ApiBase {
	constructor(baseUrl) {
		this.baseUrl = baseUrl
	}
	static getMark() {
		let mark = 'client/1'
		return mark
	}
	static stringify(obj) {
		let p = []
		for (let key in obj) {
			p.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
		}
		return p.join('&')
	}

	http(config, moduleName, args = {}) {
		let mark = ApiBase.getMark()
		const token = Data.getToken()
		const commonModule = ['Common']
		if (commonModule.includes(moduleName)) {
			mark = 'core/1'
		}
		let fullUrl = `${this.baseUrl}/${mark}/${config[1]}`
		if (moduleName == 'Export') {
			return fullUrl + '?' + ApiBase.stringify({ token, ...args })
		}
		switch (config[0]) {
			case 'PostJson':
				return axios({
					headers: { 'Content-Type': 'application/json', Token: token },
					method: 'post',
					url: fullUrl,
					params: { token },
					data: args,
				})
			case 'Post':
				return axios({
					headers: { 'Content-Type': 'application/x-www-form-urlencoded', Token: token },
					method: 'post',
					url: fullUrl,
					data: ApiBase.stringify({ token, ...args }),
				})
			case 'Get':
				return axios({
					headers: { 'Content-Type': 'application/x-www-form-urlencoded', Token: token },
					method: 'get',
					url: fullUrl,
					params: { token, ...args },
				})
		}
	}
}

class Api extends ApiBase {
	constructor(baseUrl, apiList) {
		super(baseUrl)
		for (const moduleName in apiList) {
			this[moduleName] = Object.create(null)
			const module = apiList[moduleName]
			for (const functionName in module) {
				const config = module[functionName]
				this[moduleName][functionName] = (config => {
					return (...args) => {
						return super.http(config, moduleName, ...args)
					}
				})(config)
			}
		}
	}
}

export default Api
